import { defineStore } from 'pinia'
import mockProducts from '@/data/mockProducts.json'
import { useProductStore } from './productStore'

export const useCustomerProductStore = defineStore('customerProduct', {
  state: () => ({
    products: [],
    loading: false,
    error: null
  }),

  getters: {
    getProducts: (state) => state.products,
    getProductById: (state) => (id) => state.products.find(p => p.id === id),
    getProductsByCategory: (state) => (category) => {
      if (category === '全部') return state.products
      return state.products.filter(p => p.category === category)
    }
  },

  actions: {
    async initialize() {
      this.loading = true
      this.error = null
      try {
        const productStore = useProductStore()
        await productStore.initialize() // 等待productStore初始化完成
        this.products = productStore.products // 从productStore获取数据
      } catch (error) {
        this.error = '加载商品数据失败'
        console.error('Failed to load products:', error)
      } finally {
        this.loading = false
      }
    },

    async searchProducts(query) {
      if (!query) return this.products
      const searchTerm = query.toLowerCase()
      return this.products.filter(product => 
        product.name.toLowerCase().includes(searchTerm) ||
        product.description.toLowerCase().includes(searchTerm) ||
        product.supplier.toLowerCase().includes(searchTerm)
      )
    }
  }
})